<?php


if (!function_exists('is_assoc')) {
    /**
     * 判断是否是数字数组
     * @param $arr
     * @return bool
     */
    function is_assoc($arr)
    {
        return array_keys($arr) !== range(0, count($arr) - 1);
    }
}
if(!function_exists('formatErr')){
    /**
     * 组装错误需要的数据
     * @param $e
     * @return mixed
     */
    function formatErr($e){
        $err['file'] = $e->getFile();
        $err['line'] = $e->getLine();
        $err['msg'] = $e->getMessage();
        return $err;
    }
}

if(!function_exists('getAccessToken')) {
    /**
     * 获取小程序access_token
     */
    function getAccessToken()
    {
        /*if ($type == EMPLOYEES) {
            $appID  = CUSTOMER_APPID;
            $secret = CUSTOMER_SECRET;
        } else {
            $appID  = BUSINESS_APPID;
            $secret = BUSINESS_SECRET;
        }*/
        $appID  = APP_ID;
        $secret = APP_SECRET;
        $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appID&secret=$secret";
        $result = httpGet($url);
        $json   = decodeJson($result);
        if (array_key_exists('access_token', $json)) {
            $res = $json ['access_token'];
        }

        return $res;
    }
}

if(!function_exists('decodeJson')) {
    /**
     * 解析微信返回的json数据
     * @param unknown $result
     * @return Ambigous <NULL, mixed>
     */
    function decodeJson($result)
    {
        $arr = null;
        if ($result) {
            $arr = json_decode($result, true);
            if ($arr && array_key_exists('errcode', $arr)) {
                $this->errCode = $arr ['errcode'];
                $this->errMsg  = $arr ['errmsg'];
            }
        }

        return $arr;
    }
}

if(!function_exists('httpPost')) {
    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @return string content
     */
    function httpPost($url, $param, $isArray = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (!$isArray) {
            if (is_string($param)) {
                $strPOST = $param;
            } else {
                $aPOST = array();
                foreach ($param as $key => $val) {
                    $aPOST [] = $key."=".urlencode($val);
                }
                $strPOST = join("&", $aPOST);
            }
        } else {
            $strPOST = $param;
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus  = curl_getinfo($oCurl);

        curl_close($oCurl);
        if (intval($aStatus ["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}

if(!function_exists('httpGet')) {
    /**
     * GET 请求
     * @param string $url
     */
    function httpGet($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus  = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus ["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}

if(!function_exists('get_client_ip')){
    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function get_client_ip($type = 0,$adv=true) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}

if(!function_exists('postcurl')){

    /**
     * post curl
     * @param $url
     * @param $data
     * @param $is_asyn 是否异步处理
     * @return mixed
     * @author 韩威兵^life <1877361302@qq.com>
     */
    function postcurl($url, $data , $is_asyn = false)
    {
        $ch = curl_init();
        // 定义要读取的网址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 设定为非零，代表模拟一个post操作
        curl_setopt($ch, CURLOPT_POST, 1);
        // 设置为非零，则可以传递header，设置为零则没有header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 设置为非零值，则可以捕网址读取结果，作为返回值
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 如果设置了CURLOPT_POST 为非零，则可在此设置post的具体值
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        if( $is_asyn == true ){
            curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
        }
        // 实际执行curl，因为设定了CURL_RETURNTRANSFER, 所以可以用$return 来接收返回值
        $return = curl_exec($ch);
        curl_close($ch);

        return $return;
    }
}

if(!function_exists('getcurl')){
    /**
     * 用curl执行读取网址操作.
     *
     * @param $url 需要读取的网站/接口
     *
     * @return mixed 网站/接口的返回值
     */
    function getcurl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $return = curl_exec($ch);
        curl_close($ch);

        return $return;
    }

}




if(!function_exists('awdd')) {
    /**
     * 自定义友好输出打印
     * @param $data
     */
    function awdd($data)
    {
        // 定义样式
        $str = '';
        // 如果是boolean或者null直接显示文字；否则print
        if (is_bool($data)) {
            $show_data = $data ? 'true' : 'false';
        } elseif (is_null($data)) {
            $show_data = 'null';
        } else {
            $show_data = print_r($data, true);
        }
        echo '<pre>';
        $str .= $show_data;
        $str .= '';
        echo $str;
        exit;
    }
}

if(!function_exists('aw_log')){
    /**
     * @param string $content  日志内容
     * @param string $dir   目录
     * @param string $file_name  文件名称
     * @param bool $is_end 是否追加  false 追加   true  不追加，直接覆盖
     * 2018.5.6
     */
    function aw_log($content = '', $file_name = 'debug.log', $dir='',$is_json = true, $is_end = false){
        if(empty($dir)){
            $dir = APP_PATH.'../runtime/aw_log/';
        }
        if($is_json){
            if(is_array($content) || is_object($content)){
                $content = print_r($content, true);
            }
        }else{
            if(is_array($content) || is_object($content)){
                $content = print_r($content, true);
            }
        }

        $content = ''.date('Y-m-d H:i:s').'   :@-data-@:   '.$content."  --end-->\n\r";
        if (!is_dir($dir)){
            mkdir($dir, 0777); // 使用最大权限0777创建文件
        }
        $url = $dir.$file_name;
        //判断是否是追加
        if($is_end){
            file_put_contents($url, $content);
        }else{
            file_put_contents($url, $content, FILE_APPEND);
        }
    }
}



/**
 * 判断是微信客户端还是 支付宝客户端
 * @return string
 */
function isWeixinAlipay(){
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return 'Weixin';
    }
    //判断是不是支付宝
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        echo "Alipay";
    }
    return true;
}






